#include "GameEngine/OGLConfig/Screen.h"

CPVRTglesExt m_Extensions;

#ifndef __APPLE__
static EGLDisplay	mEGLDisplay;
static EGLConfig	mEGLConfig;
static EGLContext	mEGLContext;
static EGLSurface	mEGLSurface;
#endif

bool InitOGLES(NativeDisplayType hDC,NativeWindowType m_hWnd){
#ifndef __APPLE__	
	EGLint		majorVersion=0;
	EGLint		minorVersion=0;

	mEGLDisplay=eglGetDisplay(hDC);

	if(mEGLDisplay == EGL_NO_DISPLAY){
		destroyOGLES();
		return false;
	}

	if(!eglInitialize(mEGLDisplay, &majorVersion, &minorVersion)){
		destroyOGLES();
		return false;
	}

	printf(" *** ES version %d.%d", majorVersion, minorVersion);
#endif
	printf(" *** Vendor:\n%s\n\n", (char *)glGetString(GL_VENDOR));
	printf(" *** Renderer:\n%s\n\n", (char *)glGetString(GL_RENDERER));
	printf(" *** Version:\n%s\n\n", (char *)glGetString(GL_VERSION));
	printf(" *** Extensions supported:\n%s\n\n", (char *)glGetString(GL_EXTENSIONS));
	int maxVert=0;
	glGetIntegerv(GL_MAX_VERTEX_UNITS_OES,&maxVert);
	printf(" *** GL_MAX_VERTEX_UNITS_OES:\n%d\n\n", maxVert);
	
#ifndef __APPLE__
	EGLint numConfigs = 1;

	if (eglGetConfigs(mEGLDisplay, &mEGLConfig, 1, &numConfigs) == FALSE){
		destroyOGLES();
		return false;
	}

	
	mEGLContext=eglCreateContext(mEGLDisplay, mEGLConfig, NULL, NULL);

	if (mEGLContext == EGL_NO_CONTEXT){
		destroyOGLES();
		return false;
	}

	
	mEGLSurface=eglCreateWindowSurface(mEGLDisplay, mEGLConfig, m_hWnd, NULL);

	if (mEGLSurface == EGL_NO_SURFACE){
		destroyOGLES();
		return false;
	}

	if (eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext) == false){
		destroyOGLES();
		return false;
	}
#endif
	return true;										// Initialization Went OK
}

void destroyOGLES(){
#ifndef __APPLE__
	eglMakeCurrent(EGL_NO_DISPLAY, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);

	if (mEGLContext){
		eglDestroyContext(mEGLDisplay, mEGLContext);
		mEGLContext = NULL;
	}

	if (mEGLSurface){
		eglDestroySurface(mEGLDisplay, mEGLSurface);
		mEGLSurface = NULL;
	}

	if (mEGLDisplay){
		eglTerminate(mEGLDisplay);
		mEGLDisplay = NULL;
	}
#endif
}

void flushOGLES(){
	#ifdef WIN32
		eglSwapBuffers(mEGLDisplay, mEGLSurface);
	#elif OS_IPHONE
		//glFlush();
	#endif
}
